import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_bmap/flutter_bmap.dart';
import 'package:flutter_bmap_example/views/location-view.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
    _requestPermission(); //执行权限请求
    if (Platform.isIOS == true) {
      FlutterBmap.setApiKeyForIOS("GWLRGLXxBghHDaaxxLTOluPE7ioL6NW0");
    }

    // initPlatformState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  // 动态申请定位权限
  Future<bool> _requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.location,
      Permission.storage,
    ].request();

    return statuses[Permission.location]!.isGranted &&
        statuses[Permission.storage]!.isGranted;
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion =
          await FlutterBmap.platformVersion ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        "location_view": (context) => const LocationView(),
      },
      home: const MyHome(),
    );
  }
}

class MyHome extends StatelessWidget {
  const MyHome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("地图插件"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            ListTile(
              title: const Text("定位信息"),
              subtitle: const Text("点击开始后，百度地图实时推送经纬度信息"),
              leading: const Icon(Icons.location_searching),
              trailing: const Icon(Icons.keyboard_arrow_right),
              onTap: () {
                Navigator.pushNamed(context, "location_view");
              },
            )
          ],
        ),
      ),
    );
  }
}
